package manager.config;
import common.JksUtils;
import manager.auth.dao.*;
import manager.auth.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import tk.mybatis.mapper.entity.Example;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Component
public class AuthInteceptor implements HandlerInterceptor {
    @Autowired
    private SysPermissionDao sysPermissionDao;
    @Autowired
    private SysUserRoleDao sysUserRoleDao;
    @Autowired
    private SysRolePermissionDao sysRolePermissionDao;
    private static final ThreadLocal<UserInfo> USER_INFO = new ThreadLocal<>();
    private static final ThreadLocal<UserInfo> ADMIN_USER_INFO = new ThreadLocal<>();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String reqUri=request.getRequestURI();
        if(reqUri.equals("/admin/auth/login")||reqUri.equals("/admin/auth/verify")||reqUri.equals("/admin/auth/unaccredit")){
            return true;
        }
        Cookie[] cookies = request.getCookies();
        if(cookies.equals(null)){
            response.getWriter().write("403");
            return false;
        }
        String token;
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("shop_tick_tocken")) {
                token = cookie.getValue();
                Map<String,Object> userInfoMap= JksUtils.getUserInfoByToken(token);
                String username=(String)userInfoMap.get("username");
                UserInfo userInfo=new UserInfo();
                userInfo.setUsername(username);
                USER_INFO.set(userInfo);
            }
            if (cookie.getName().equals("shop_admin_tick_tocken")) {
                token = cookie.getValue();
                Map<String,Object> userInfoMap= JksUtils.getUserInfoByToken(token);
                String username=(String)userInfoMap.get("username");
                String userId=(String)userInfoMap.get("userId");
                UserInfo userInfo=new UserInfo();
                userInfo.setId(Long.parseLong(userId));
                userInfo.setUsername(username);
                ADMIN_USER_INFO.set(userInfo);
            }
        }
        if(!reqUri.startsWith("/customer")){
            boolean hasPermission=hasPermission(handler);
            if(!hasPermission){
                response.getWriter().write("10001");
                return false;
            }
        }

        return true;
    }
    private boolean hasPermission(Object handler){
        //判断用户是否有权限
        UserInfo userInfo=getAdminUserInfo();
        if(userInfo==null){
            return false;
        }
        if(userInfo.getUsername().equals("admin")){
            return true;
        }
        SysUserRoleVO sysUserRoleVO=new SysUserRoleVO();
        sysUserRoleVO.setUserId(String.valueOf(userInfo.getId()));
        List<SysUserRoleVO> userRoleList=sysUserRoleDao.select(sysUserRoleVO);
        Example rolePermissionExample = new Example(SysRolePermissionVO.class);
        List<String> roleIdList=userRoleList.stream().map(item->item.getRoleId()).collect(Collectors.toList());
        if(roleIdList.size()==0){
            return false;
        }
        rolePermissionExample.createCriteria().andIn("roleId",roleIdList);
        List<SysRolePermissionVO> sysRolePermissionList=sysRolePermissionDao.selectByExample(rolePermissionExample);
        //获取所有的权限
        List<String> permissionIdList=sysRolePermissionList.stream().map(item->item.getPermissionId()).collect(Collectors.toList());
        if(permissionIdList.size()==0){
            return false;
        }
        Example permissionExample = new Example(SysPermissionVO.class);
        permissionExample.createCriteria().andIn("id",permissionIdList);
        List<SysPermissionVO> permissionList= sysPermissionDao.selectByExample(permissionExample);
        //自定义注解解析
        if (handler instanceof HandlerMethod){
            HandlerMethod method = (HandlerMethod)handler;
            RequiredPermission methodPermission = method.getMethodAnnotation(RequiredPermission.class);
            if(methodPermission==null){
                return true;
            }
            String permissionCode=methodPermission.module()+"_"+methodPermission.code();
            List<SysPermissionVO> list= permissionList.stream().filter(item->item.getCode().equals(permissionCode)).collect(Collectors.toList());
            if(list.size()>0){
                return true;
            }
        }
        return false;
    }
    //根据条件获取用户
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        USER_INFO.get();
        ADMIN_USER_INFO.get();
    }

    public  static  UserInfo getUserInfo(){
         return USER_INFO.get();
    }
    public  static  UserInfo getAdminUserInfo(){
        return ADMIN_USER_INFO.get();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        USER_INFO.remove();
        ADMIN_USER_INFO.remove();
    }
}
